package com.itheima.health.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class Filter implements javax.servlet.Filter {

    //定义白名单url，不需要登录就能访问的url
    private String[] whiteList={
            "/user/login",
            "/user/logout",
            "/common/**",
            "/mobile/**"
    };

    //定义一个map集合，存放需要权限的页面，key为页面url  value为该页面的权限。
    Map<String,String> permissionsUrl=new HashMap<>();//存在在初始化方法

    @Autowired
    private UserService userService;


    /**
     * 初始化方法
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig config) throws ServletException {
        //在过滤器创建的时候就要加载进map中
        permissionsUrl.put("/checkitem/delete","CHECKITEM_DELETE");
        permissionsUrl.put("/checkgroup/delete","CHECKGROUP_DELETE");
        permissionsUrl.put("/setmeal/delete","SETMEAL_DELETE");
        permissionsUrl.put("/report/**","REPORT_VIEW");

    }


    /**
     * 核心方法
     * @param request
     * @param response
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //将Servlet请求对象和响应对象 强转 为HttpServlet请求对象和响应对象
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;

        AntPathMatcher matcher =new AntPathMatcher(); //创建路径匹配器
        //获取当前用户在前端的请求url
        String requestURI = req.getRequestURI();

        //与白名单的url进行对比
        for (String whiteUrl : whiteList) {
            boolean match = matcher.match(whiteUrl, requestURI);
            if (match){
                //是白名单的内容放行
                chain.doFilter(request,response);
                return;
            }
        }
        //如果不是白名单的进行非法登录验证
        User user = (User) req.getSession().getAttribute("user");
        if (user==null){
            //证明没有登录，让他去登录
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(new Result(false, "请重新登录陆")));
            return;
        }

        //走到这里就是登录了，但是还要看访问的是页面需要什么权限，权限不匹配不放行

        //获取当前登录的用户的权限
        List<String> userPermissionList = userService.findPermissions(user.getUsername());
        //获取permissionsUri map集合的所有key即需要权限的uri
        Set<String> set = permissionsUrl.keySet();
        log.info("请求uri是{}",requestURI);
        for (String s : set) {
            //相同证明现在访问的uri需要权限
            if (matcher.match(s,requestURI)){
                //获取当前的uri权限
                String permission = permissionsUrl.get(s);
                //判断当前用户登录有无此权限
                for (String userPermission : userPermissionList) {
                    if (permission.equals(userPermission)){
                        //用户有权限放行
                        chain.doFilter(request,response);
                        return;
                    }
                }
                //没有权限不让访问
                response.setContentType("application/json; charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(new Result(false, "无操作权限")));
                return;
            }
        }
        //走到这里证明不需要权限了
        chain.doFilter(request,response);
        return;
    }


    /**
     * 摧毁方法
     */
    @Override
    public void destroy() {

    }
}
